package com.carrental.rental.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.carrental.rental.dto.ContractDTO;
import com.carrental.rental.entity.Contract;
import com.carrental.rental.mapper.ContractMapper;
import com.carrental.rental.service.ContractService;
import com.carrental.rental.vo.ContractVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 合同服务实现类
 */
@Service
public class ContractServiceImpl extends ServiceImpl<ContractMapper, Contract> implements ContractService {

    /**
     * 创建合同
     *
     * @param contractDTO 合同DTO
     * @return 合同ID
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createContract(ContractDTO contractDTO) {
        // 生成合同号
        String contractNo = generateContractNo();
        
        Contract contract = new Contract();
        BeanUtils.copyProperties(contractDTO, contract);
        contract.setContractNo(contractNo);
        contract.setStatus(1); // 默认状态为待签署
        contract.setCreateTime(LocalDateTime.now());
        contract.setUpdateTime(LocalDateTime.now());
        
        // 保存合同
        save(contract);
        
        return contract.getId();
    }

    /**
     * 根据ID获取合同详情
     *
     * @param id 合同ID
     * @return 合同VO
     */
    @Override
    public ContractVO getContractById(Long id) {
        Contract contract = getById(id);
        if (contract == null) {
            return null;
        }
        
        return convertToVO(contract);
    }

    /**
     * 根据合同号获取合同详情
     *
     * @param contractNo 合同号
     * @return 合同VO
     */
    @Override
    public ContractVO getContractByContractNo(String contractNo) {
        LambdaQueryWrapper<Contract> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Contract::getContractNo, contractNo);
        
        Contract contract = getOne(wrapper);
        if (contract == null) {
            return null;
        }
        
        return convertToVO(contract);
    }

    /**
     * 根据订单ID获取合同详情
     *
     * @param orderId 订单ID
     * @return 合同VO
     */
    @Override
    public ContractVO getContractByOrderId(Long orderId) {
        LambdaQueryWrapper<Contract> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Contract::getOrderId, orderId);
        
        Contract contract = getOne(wrapper);
        if (contract == null) {
            return null;
        }
        
        return convertToVO(contract);
    }

    /**
     * 分页查询用户合同
     *
     * @param page   分页参数
     * @param userId 用户ID
     * @param status 合同状态
     * @return 分页合同VO
     */
    @Override
    public Page<ContractVO> pageUserContracts(Page<Contract> page, Long userId, Integer status) {
        LambdaQueryWrapper<Contract> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Contract::getUserId, userId);
        wrapper.eq(status != null, Contract::getStatus, status);
        wrapper.orderByDesc(Contract::getCreateTime);
        
        Page<Contract> contractPage = page(page, wrapper);
        
        return convertToVOPage(contractPage);
    }

    /**
     * 分页查询所有合同
     *
     * @param page       分页参数
     * @param contractNo 合同号
     * @param orderNo    订单号
     * @param userId     用户ID
     * @param status     合同状态
     * @return 分页合同VO
     */
    @Override
    public Page<ContractVO> pageContracts(Page<Contract> page, String contractNo, String orderNo, Long userId, Integer status) {
        LambdaQueryWrapper<Contract> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(contractNo), Contract::getContractNo, contractNo);
        wrapper.like(StringUtils.isNotBlank(orderNo), Contract::getOrderNo, orderNo);
        wrapper.eq(userId != null, Contract::getUserId, userId);
        wrapper.eq(status != null, Contract::getStatus, status);
        wrapper.orderByDesc(Contract::getCreateTime);
        
        Page<Contract> contractPage = page(page, wrapper);
        
        return convertToVOPage(contractPage);
    }

    /**
     * 签署合同
     *
     * @param id 合同ID
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean signContract(Long id) {
        Contract contract = getById(id);
        if (contract == null) {
            return false;
        }
        
        // 检查合同状态是否为待签署
        if (contract.getStatus() != 1) {
            return false;
        }
        
        // 更新合同状态为已签署
        contract.setStatus(2);
        contract.setSignTime(LocalDateTime.now());
        // 设置合同有效期为一年
        contract.setExpireTime(LocalDateTime.now().plusYears(1));
        contract.setUpdateTime(LocalDateTime.now());
        
        return updateById(contract);
    }

    /**
     * 使合同失效
     *
     * @param id 合同ID
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean invalidateContract(Long id) {
        Contract contract = getById(id);
        if (contract == null) {
            return false;
        }
        
        // 检查合同状态是否为已签署
        if (contract.getStatus() != 2) {
            return false;
        }
        
        // 更新合同状态为已失效
        contract.setStatus(3);
        contract.setUpdateTime(LocalDateTime.now());
        
        return updateById(contract);
    }

    /**
     * 生成合同号
     */
    private String generateContractNo() {
        // 生成格式为：C + 当前时间（年月日）+ 8位随机数
        String timeStr = LocalDateTime.now().toString().substring(0, 10).replaceAll("-", "");
        String randomStr = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 8);
        return "C" + timeStr + randomStr;
    }

    /**
     * 转换合同实体为VO
     */
    private ContractVO convertToVO(Contract contract) {
        if (contract == null) {
            return null;
        }
        
        ContractVO vo = new ContractVO();
        BeanUtils.copyProperties(contract, vo);
        
        // 设置合同状态名称
        vo.setStatusName(getStatusName(contract.getStatus()));
        
        // TODO: 调用用户服务获取用户信息
        
        return vo;
    }

    /**
     * 转换合同分页为VO分页
     */
    private Page<ContractVO> convertToVOPage(Page<Contract> page) {
        Page<ContractVO> voPage = new Page<>();
        voPage.setCurrent(page.getCurrent());
        voPage.setSize(page.getSize());
        voPage.setTotal(page.getTotal());
        
        List<ContractVO> voList = page.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
        
        voPage.setRecords(voList);
        return voPage;
    }

    /**
     * 获取合同状态名称
     */
    private String getStatusName(Integer status) {
        if (status == null) {
            return "";
        }
        
        switch (status) {
            case 1:
                return "待签署";
            case 2:
                return "已签署";
            case 3:
                return "已失效";
            default:
                return "未知状态";
        }
    }
} 